package com.loe.mvp.initer

import android.app.Activity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import android.graphics.PixelFormat
import android.os.Handler
import android.os.Looper
import androidx.annotation.LayoutRes
import androidx.fragment.app.FragmentActivity
import android.view.*
import android.view.animation.AccelerateInterpolator
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.widget.TextView
import com.loe.mvp.R
import com.loe.mvp.ext_app.inflate

/**
 * 自定义toast
 * （不受禁止通知影响）
 */
open class StyleToast(activity: Activity, @LayoutRes reLayout: Int)
{
    private val activity: Activity = activity
    private val layout: ViewGroup = activity.inflate(reLayout, null) as ViewGroup
    private val content: View = layout.getChildAt(0)
    private val startAnimation: Animation
    private val centerAnimation: Animation
    private val endAnimation: Animation
    private var task: DelayTask? = null
    private var isShow = false
    private val params: WindowManager.LayoutParams = WindowManager.LayoutParams()

    var duration = 1800
    var gravity: Int = Gravity.CENTER

    open fun ViewGroup.onView(msg: String)
    {
        try
        {
            findViewById<TextView>(R.id.textView).text = msg
        }catch (e: Exception)
        {
        }
    }

    /**
     * APP级别Toast
     */
    init
    {
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        params.width = WindowManager.LayoutParams.MATCH_PARENT
        params.gravity = gravity
        params.type = WindowManager.LayoutParams.TYPE_APPLICATION
        params.format = PixelFormat.TRANSLUCENT
        params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
        layout.visibility = View.GONE

        // 开始动画
        startAnimation = AlphaAnimation(0f, 1f)
        startAnimation.setDuration(500)

        // 中间动画
        centerAnimation = AlphaAnimation(0.92f, 1f)
        centerAnimation.setDuration(500)

        // 结束动画
        endAnimation = AlphaAnimation(1f, 0f)
        endAnimation.setDuration(500)
        endAnimation.setInterpolator(AccelerateInterpolator())

        // 结束动画监听
        endAnimation.setAnimationListener(object : Animation.AnimationListener
        {
            override fun onAnimationStart(animation: Animation)
            {
            }

            override fun onAnimationEnd(animation: Animation)
            {
                layout.visibility = View.GONE
                activity.windowManager.removeView(layout)
            }

            override fun onAnimationRepeat(animation: Animation)
            {
            }
        })

        if (activity is FragmentActivity)
        {
            activity.lifecycle.addObserver(object : LifecycleObserver
            {
                @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                fun onDestroy()
                {
                    try
                    {
                        activity.windowManager.removeViewImmediate(layout)
                    } catch (e: Exception)
                    {
                    }
                }
            })
        }
    }

    /**
     * 显示Toast
     */
    fun show(msg: Any, delay: Int = duration)
    {
        try
        {
            activity.windowManager.addView(layout, params)
        } catch (e: Exception)
        {
        }
        try
        {

            layout.onView(msg.toString())
        } catch (e: Exception)
        {
        }
        start()
        if (task != null)
        {
            task?.stop()
        }
        task = object : DelayTask(delay.toLong())
        {
            public override fun run()
            {
                end()
            }
        }
        task?.start()
    }

    /**
     * 开始
     */
    private fun start()
    {
        if (!isShow)
        {
            layout.visibility = View.VISIBLE
            content.startAnimation(startAnimation)
            isShow = true
        } else
        {
            content.startAnimation(centerAnimation)
        }
    }

    /**
     * 结束
     */
    private fun end()
    {
        content.startAnimation(endAnimation)
        isShow = false
    }

    internal abstract class DelayTask(private var delay: Long = 0L) : Handler(Looper.getMainLooper())
    {
        private val runnable = Runnable { this@DelayTask.run() }
        fun start()
        {
            if (delay == 0L)
            {
                post(runnable)
            } else
            {
                postDelayed(runnable, delay)
            }
        }

        fun stop()
        {
            removeCallbacks(runnable)
        }

        protected abstract fun run()
    }
}